import { wss } from '../ws.js'
import { nanoid } from 'nanoid'
import { movePoint } from '../utils/tools.js'
import { getMonster } from './monster.js'

const data = [
  {
    id: nanoid(),
    name: '主角',
    type: 'p1',
    x: 1,
    y: 1,
    // x: Math.floor(Math.random() * 12),
    // y: Math.floor(Math.random() * 10),
    hp: 600,
    rHp: 600,
    maxAtk: 5,
    minAtk: 20,
    critRate: 0.15, //暴击几率
    critDmg: 1.5, //暴击伤害
  },
]
const coordinates = []
data.map((item) => {
  coordinates.push(item)
})

wss.on('connection', (ws) => {
  ws.on('error', console.error)

  // init(ws)
  ws.send(
    JSON.stringify({
      type: 'player',
      data: coordinates,
    })
  )
  ws.on('message', (data) => {
    const res = JSON.parse(data)
    if (res.type === 'attack') {
      console.log(res.data)
      const targets = inAttackRange(coordinates[0], getMonster())
      conductBattle(coordinates[0], targets)
      ws.send(
        JSON.stringify({
          type: 'monster',
          data: targets,
        })
      )
      ws.send(
        JSON.stringify({
          type: 'player',
          data: coordinates,
        })
      )
    }
  })
})

function conductBattle(player, targets) {
  for (let i = 0; i < targets.length; i++) {
    const target = targets[i]
    calculateDamage(player, target)
    calculateDamage(target, player)
  }
}

function calculateDamage(attacker, defender) {
  const maxAtk = attacker.maxAtk
  const minAtk = attacker.minAtk
  let atk = Math.floor(Math.random() * (maxAtk - minAtk + 1)) + minAtk
  if (Math.random() < attacker.critRate) {
    atk *= attacker.critDmg
  }
  let rHp = defender.rHp - atk
  defender.rHp = rHp <= 0 ? 0 : rHp
}

function inAttackRange(playerPosition, targetsPositions, attackRange = 1) {
  const targetsInRange = []

  for (let i = 0; i < targetsPositions.length; i++) {
    const dx = targetsPositions[i].x - playerPosition.x
    const dy = targetsPositions[i].y - playerPosition.y
    const distance = Math.sqrt(dx * dx + dy * dy)

    if (distance <= attackRange) {
      targetsInRange.push(targetsPositions[i])
    }
  }
  return targetsInRange
}

let timer = null

function init(ws) {
  for (let i = 0; i < coordinates.length; i++) {
    const item = coordinates[i]
    movePoint(item)
  }

  const result = {
    type: 'player',
    data: coordinates,
  }
  ws.send(JSON.stringify(result))

  clearTimeout(timer)
  timer = setTimeout(() => init(ws), 1200)
}
